"""
@filename: adminapi.py
@project: flask_project
@author: wlf
@time: 2022-09-07
"""
from flask_restful import Resource, Api
from flask import Blueprint, request, session
from model import db
from libs.response import generate_response
from model.admin import Admin
from model.school import School
from model.user import UserManager
from sqlalchemy import or_

admin_bp = Blueprint("adminapi", __name__, url_prefix="/v1")
api = Api(admin_bp)


class AdminView(Resource):
    def post(self):
        user_id = request.json.get("user_id")
        school_id = request.json.get("school_id")

        query_user_id = UserManager.query.get(user_id)
        query_school_id = School.query.get(school_id)

        if query_user_id is not None:
            if query_school_id is not None:
                admin_info = Admin(
                    user_id=user_id,
                    school_id=school_id
                )

                db.session.add(admin_info)
                db.session.commit()

                return generate_response(message="post user success")
            else:
                return generate_response(status_code=10001, message="school doesn't exist")
        else:
            return generate_response(status_code=10001, message="user doesn't exist")

    def get(self, id=None):
        keyword = request.args.get("keyword")
        result_list = []
        if id is not None:
            admin_info = Admin.query.get(id)
            if admin_info is not None:
                result_list.append(admin_info)
            else:
                return generate_response(status_code=10001, message="amidn_id not found")
        else:
            if keyword is not None:
                admins_info = Admin.query.filter(or_(Admin.user_id.like('%'+keyword+'%'), Admin.school_id.like('%'+keyword+'%'))).all()
            else:
                admins_info = Admin.query.all()
            result_list += admins_info

        return generate_response(message="search success", data=[user.to_json1() for user in result_list])

    def delete(self):
        pass

    def update(self):
        pass


api.add_resource(AdminView, "/admin")
api.add_resource(AdminView, "/admin/<int:id>", endpoint="adminviewapi")